<template>
	<div class="addBox">
		<div class="addBoxTop">
			<div v-if="detailsId">
				<span class="font_size20">积分规则</span>
			</div>
			<div v-else class="font_size20">积分规则</div>
		</div>
		<div class="addDiv" v-loading="sLoading">
			<el-form ref="form" :model="objectForm" :rules="objectRules" label-width="140px">
				<el-form-item label="使用云店" prop="shopid_yd">
					<el-select v-model="objectForm.shopid_yd" placeholder="请选择"
						:disabled="isDisabled || isDisbableInfo.type || isDidd">
						<el-option v-for="item in getYunShopsList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="'规则名称'" prop="title">
					<el-input v-model="objectForm.title" class="input-w" placeholder="请填写标题, 20个文字内" maxlength="20"
						show-word-limit :disabled="isDisabled || isDisbableInfo.type"></el-input>
				</el-form-item>
				<el-form-item label="积分规则" prop="isbase">
					<el-select v-model="objectForm.isbase" placeholder="请选择"
						:disabled="isDisabled || isDisbableInfo.type || isDidd" @change="handleIsbaseChange">
						<el-option v-for="item in fractTypeList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<template v-if="objectForm.isbase == 1">
					<el-form-item :label="'积分有效期'" prop="y_stop">
						<el-date-picker v-model="objectForm.y_stop" type="year" placeholder="请选择年份"
							:disabled="isDisabled || isDisbableInfo.type" format="yyyy" value-format="yyyy"
							:picker-options="pickerOptions"></el-date-picker>
					</el-form-item>
					<el-form-item :label="'积分获取上限'" prop="p_top">
						<el-input-number v-model="objectForm.p_top" controls-position="right" :min="0" :max="99999"
							style="width: 220px; text-align: left;" :precision="0" class="el-input-xnumber-box"
							:disabled="isDisabled || isDisbableInfo.type"></el-input-number>
						<span class="tip-text font_red">（ 每个客户最多获取99999积分，0为不限制 ）</span>
					</el-form-item>
				</template>
				<template v-if="objectForm.isbase == 2">
					<el-form-item label="积分获取类型" prop="type">
						<el-select v-model="objectForm.type" placeholder="请选择"
							:disabled="isDisabled || isDisbableInfo.type || isDidd" @change="handleTypeChange">
							<el-option v-for="item in getTypeLsSys" :key="item.id" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="'每购买金额'" prop="m" v-if="currentTypeName.includes('金额')">
						<el-input v-model="objectForm.m" placeholder="请填写每购买金额" :min="0" style="width: 217px;"
							:disabled="isDisabled || isDisbableInfo.type" @input="handlePriceInput"></el-input>
						<span class="tip-text">(元)</span>
					</el-form-item>
					<el-form-item :label="`${currentTypeTxt}`" prop="p">
						<el-input-number v-model="objectForm.p" controls-position="right" :min="0" :max="99999"
							style="width: 220px;" :precision="0" :disabled="isDisabled || isDisbableInfo.type"
							class="el-input-xnumber-box"></el-input-number>
						<span class="tip-text">(积分)</span>
					</el-form-item>
				</template>
				<el-form-item label="备注" prop="txt">
					<el-input type="textarea" v-model="objectForm.txt" class="input-w" placeholder="请填写备注"
						show-word-limit :disabled="isDisabled || isDisbableInfo.type"></el-input>
				</el-form-item>
				<el-form-item label="启用" prop="value1">
					<div class="switchDiv">
						<el-switch v-model="objectForm.value1"
							:disabled="isDisabled || isDisbableInfo.type"></el-switch>
					</div>
				</el-form-item>
			</el-form>
		</div>
		<div class="addDivBtn">
			<div class="acvite-btn" v-if="objectForm.status == 2" @click="stopActivity">停止</div>
			<div class="acvite-btn" v-else-if="btnShow" @click="createActivity">提交</div>
			<div class="back-btn" @click="goBack" v-if="objectForm.act == 'add'">返回</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, getCurrentInstance, watch, computed, defineExpose } from '@vue/composition-api'
import config from "@/js/conf/Config.js"
import { priceInput } from '@/utils/common.js'
import { fractTypeList, ptypeList } from '@/utils/dict.js'

// 获取当前组件实例
const { proxy } = getCurrentInstance()
const props = defineProps({
	getYunShopList: {
		type: Array,
		default: () => [],
	},
	typeLsSys: {
		type: Array,
		default: () => [],
	},
	detailID: {
		type: String,
		default: "",
	},
	// 如果是编辑页面，设置某些值不能编辑
	isDisbableInfo: {
		type: Object,
		default: () => ({
			type: false,
		}),
	},
})

const emit = defineEmits(['addTpBmFun'])
const form = ref(null)
const sLoading = ref(false)

const objectForm = ref({
	act: "add",
	id: "",
	shopid_yd: "",
	title: "", // 规则名称
	isbase: "", // 是否通用规则1是2否=自定义【不可更改】
	m: "", // 每购买金额
	p: "", // 单笔奖励积分
	type: '', // 积分获取类型 类型 1订单金额 2订单数量 3一级分销 4二级分销  7.签到赠送【不可更改】
	p_top: "", // 积分获取上限
	y_stop: "", // 积分有效期
	txt: "", // 备注
	status: '', // 启用
	value1: true, // 启用
})

const btnShow = computed(() => {
	return objectForm.value.status == 1 || (props.isDisbableInfo.index_key == '-1' && objectForm.act == 'add') || (props.isDisbableInfo.index_key != '3')
})

const objectRules = ref({
	shopid_yd: [
		{ required: true, message: '请选择云店', trigger: 'change' }
	],
	title: [
		{ required: true, message: '请填写标题', trigger: 'blur' }
	],
	isbase: [
		{ required: true, message: '请选择积分等级', trigger: 'change' }
	],
	ptype: [
		{ required: true, message: '请选择分润获取类型', trigger: 'change' }
	],
	p_top: [
		{ required: true, message: '请填写获取积分', trigger: 'blur' }
	],
	y_stop: [
		{ required: true, message: '请填写积分有效期', trigger: 'blur' }
	],
	type: [
		{ required: true, message: '请选择积分获取类型', trigger: 'change' }
	],
	m: [
		{ required: true, message: '请填写每购买金额', trigger: 'blur' }
	],
	p: [
		{ required: true, message: '请填写单笔奖励积分', trigger: 'blur' }
	],
})


const handleIsbaseChange = (val) => {
	if (val == 1) {
		objectRules.value.type[0].required = false
	} else {
		objectRules.value.type[0].required = true
	}
	objectForm.value.p_top = ''
	objectForm.value.m = ''
	objectForm.value.p = ''
	objectForm.value.type = ''
}

const handleTypeChange = (val) => {
	objectForm.value.m = ''
	objectForm.value.p = ''
}

const getYunShopsList = computed(() => {
	return props.getYunShopList
})

const getTypeLsSys = computed(() => {
	return props.typeLsSys
})

const currentTypeName = computed(() => {
	const found = getTypeLsSys.value.find(item => item.id == objectForm.value.type)
	return found ? found.name : ''
})

// 类型 1订单金额 2订单数量 3一级分销 4二级分销  7.签到赠送【不可更改】
const currentTypeTxt = computed(() => {
	const found = getTypeLsSys.value.find(item => item.id == objectForm.value.type)
	console.log("found=>", found)
	let txt = '单笔奖励积分'
	if (found) {
		if (found?.name.includes('金额')) {
			txt = '单笔奖励积分'
		} else if (found?.name.includes('分销')) {
			txt = '单人奖励积分'
		} else if (found?.id == 7) {
			txt = '签到赠送'
		}
	}
	return txt
})

// 日期选择器配置 - 限制只能从现年开始选择
const pickerOptions = ref({
	disabledDate(time) {
		return time.getTime() < new Date(new Date().getFullYear(), 0, 1).getTime()
	}
})

const restFun = () => {
	objectForm.value.id = "";
	objectForm.value.act = 'add';
	objectForm.value.p_top = "";
	objectForm.value.y_stop = "";
	detailsId.value = '';
	form.value?.resetFields();
}

const submitForm = async (formName) => {
	console.log("objectForm.value=", objectForm.value)
	const valid = await form.value?.validate()
	if (valid) {
		const params = {
			...objectForm.value,
			status: objectForm.value.value1 ? 2 : 1,
		}
		const res = await proxy.$api({ url: config.yx_jf_event_save, data: params })
		if (res.status == 1) {
			proxy.$message.success(res?.msg || '操作成功')
			emit("addTpBmFun", {
				type: objectForm.value.act,
				status: objectForm.value.value1 ? 2 : 1,
			})
		} else {
			proxy.$message.error(res?.msg || '操作失败')
		}
	}
}

const createActivity = () => {
	submitForm("form")
}

const stopActivity = async () => {
	proxy.$confirm(`此操作将停止【${objectForm.value.title}】规则, 是否继续?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		let params = {
			...objectForm.value,
			isbase: objectForm.value.isbase.toString(),
			act: 'stop',
			status: 3,
		}
		let res = await proxy.$api({ url: config.yx_jf_event_save, data: params });
		if (res.status == 1) {
			proxy.$message({
				message: '停止成功',
				type: 'success'
			});
			emit("addTpBmFun", {
				type: 'del',
				status: 3,
			})
		} else {
			proxy.$message({
				message: res?.msg || '停止失败',
				type: 'error'
			})
		}
	})
}

const goBack = () => {
	emit("backFun", 'back')
}

// 获取详情
const getDetail = async () => {
	sLoading.value = true
	const res = await proxy.$api({ url: config.yx_jf_event_info, data: { id: props.detailID } }).finally(() => {
		setTimeout(() => {
			sLoading.value = false
		}, 200)
	})
	if (res.status === 1 && res.data) {
		// 将获取到的数据赋值到 objectForm
		const data = res.data
		objectForm.value.id = data.id;
		objectForm.value = {
			...objectForm.value,
			...data,
			act: 'edt',
			isbase: Number(data.isbase),
			p_top: Number(data.p_top),
			m: Number(data.m),
			p: Number(data.p),
			value1: data.status == 2 ? true : false,
		}
		console.log("objectForm.value=", objectForm.value)
	}
}

// 修改 watch 实现
const detailsId = ref("")
watch(() => props.detailID, (newVal) => {
	console.log("newVal=xxxx", newVal)
	setTimeout(() => {
		if (newVal) {
			detailsId.value = newVal
			getDetail()
			form.value?.resetFields()
		}
		if (!newVal) {
			restFun()
		}
	}, 200)
}, { immediate: true })

onMounted(() => { })

// 添加计算属性
const isDisabled = computed(() => {
	const disabledStatus = ['2', '3']
	return disabledStatus.includes(objectForm.value.status)
})

const isDidd = computed(() => {
	const disabledStatus = ['1']
	return disabledStatus.includes(objectForm.value.status)
})


const handlePriceInput = (value) => {
	objectForm.value.m = priceInput(value)
}


defineExpose({
	restFun,
	objectForm
})

</script>

<style lang="scss" scoped>
.addBox {
	width: 100%;
	box-sizing: border-box;

	.addDivBtn {
		width: 100%;
		height: 60px;
		line-height: 60px;
		text-align: right;
		border-top: 1px solid #E4E7ED;

		>div {
			display: inline-block;
			background: #3388ff;
			font-size: 16px;
			height: 100%;
			color: #FFFFFF;
			text-align: center;
			padding: 0 20px;
			cursor: pointer;
			border-right: 1px solid #FFFFFF;

			&:last-child {
				border: none;
			}
		}

		.back-btn {
			background: #ece8e8;
			color: #333;
			border-right: 1px solid #ececec;
		}
	}

	.addBoxTop {
		width: 100%;
		height: 40px;
		border-bottom: 2px solid #E4E7ED;
		margin-bottom: 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.addDiv {
		box-sizing: border-box;
		width: 100%;
		padding-right: 100px;
		height: calc(100vh - 57px - 70px);
		overflow-y: auto;

		.switchDiv {
			height: 40px;
			display: flex;
			align-items: center;

			span {
				margin-right: 20px;
			}
		}

		.timeShowBox {
			// width: 600px;
			height: 40px;
			border: 1px solid #DCDFE6;
			border-radius: 5px;
			cursor: pointer;

			.timeShowdiv {
				padding: 0 10px;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;

				span {
					margin-right: 10px;

					&:last-child {
						margin-right: 0;
					}
				}
			}
		}
	}

	::v-deep.mb-box {
		margin-bottom: 10px;

		&:last-child {
			margin: 0;
		}

		.el-radio__label {
			display: none;
		}

		.pl-box {
			font-size: 14px;
			margin-bottom: 10px;
			display: flex;
			align-items: center;
			cursor: pointer;

			span {
				margin-right: 10px;
			}

			img {
				margin-right: 10px;
				width: 25px;
				height: 25px;
			}

			.txt-box {
				width: 145px;
				display: flex;
				align-items: center;
			}
		}

		.color-box {
			display: flex;
			font-size: 14px;

			.color-row {
				margin-right: 10px;
				text-align: center;
				cursor: pointer;

				.color-title {
					font-size: 12px;
					margin: 10px 0;
				}

				.background-item {
					width: 80px;
					height: 80px;
				}
			}
		}
	}
}

.tip-text {
	font-size: 12px;
	color: #666;
	margin-left: 10px;
}



::v-deep .el-color-picker__color {
	border: none !important;
}

::v-deep .el-color-picker__color-inner {
	border: none !important;
}

::v-deep .el-color-picker__mask {
	display: none !important;
}

.ml20 {
	margin-left: 20px;
}

.switch-mode {
	color: #3388ff;
	cursor: pointer;
}

.disabled-btn {
	opacity: 0.5;
	cursor: not-allowed;
	pointer-events: none;
}

.acvite-btn {
	opacity: 1;
	cursor: pointer;
}

::v-deep .el-icon-close:before {
	content: "\e6df";
}

::v-deep .el-input.is-disabled .el-input__inner,
::v-deep .el-textarea.is-disabled .el-textarea__inner {
	background-color: #fcfcfc !important;
	color: #666 !important;
	border-color: #f1f1f1 !important;
}

.profit-box {
	margin-left: 20px;
	padding: 20px;
	background-color: #f5f7fa;
	border-radius: 5px;

	img {
		width: 250px;
		height: 130px;
	}
}

::v-deep .el-input-xnumber-box {
	.el-input__inner {
		text-align: left !important;
	}
}
</style>